const mongoose = require('mongoose');

const Product = require('./product');

const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    cart: {
        items: [
            {
                prodId: {
                    type: mongoose.Types.ObjectId,
                    required: true,
                    ref: 'Product'
                },
                quantity: {
                    type: Number,
                    required: true
                }
            }
        ]
    }
})

userSchema.methods.addToCart = function (prodId) {
    const findFetchProdIndex = this.cart.items.findIndex(item => item.prodId.toString() === prodId);
    if (findFetchProdIndex !== -1) {
        let item = this.cart.items[findFetchProdIndex];
        item.quantity += 1;
    } else {
        this.cart.items.push({
            prodId: prodId,
            quantity: 1
        })
    }
    return this.save()
}
userSchema.methods.getCart = function () {
    const prodIds = this.cart.items.map(item => item.prodId);
    return Product.find({ _id: { $in: prodIds } })
    .then(products => {
        return products.map(prod => {
            return {
                ...prod._doc,
                quantity: this.cart.items.find(item => item.prodId.toString() === prod._id.toString()).quantity
            }
        })
    })
}
userSchema.methods.deleteFromCart = function (prodId) {
    const newItems = this.cart.items.filter(item => item.prodId.toString() !== prodId)
    this.cart.items = newItems;
    return this.save()
}

userSchema.methods.clearCart = function () {
    this.cart.items = [];
    return this.save();
}

module.exports = mongoose.model('User', userSchema);